const express = require("express");
const router = express.Router();

const { Article } = require("../models");

router.get("/articles/list", async (req, res) => {
  try {
    const where = {
      order: [["id", "DESC"]],
    };
    const result = await Article.findAll(where);
    response.success(res, result);
  } catch (e) {
    response.fail(res, "查询文章列表失败");
  }
});

router.get("/articles/detail/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const result = await Article.findByPk(id);
    if (result) {
      response.success(res, result);
    } else {
      response.error(res, "查询文章失败");
    }
  } catch (e) {
    response.fail(res, "查询文章列表失败",e);
  }
});

router.post("/articles/add", async (req, res) => {
  try {
    const { title, content } = req.body;
    const result = await Article.create({
      title,
      content,
    });
    response.msgShow(res, result);
  } catch (e) {
    response.fail(res, "添加文章失败");
  }
});

module.exports = router;
